{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Linear Regression Implementation from Scratch\n",
    ":label:`sec_linear_scratch`\n",
    "\n",
    "Now that you understand the key ideas behind linear regression,\n",
    "we can begin to work through a hands-on implementation in code.\n",
    "In this section, we will implement the entire method from scratch,\n",
    "including the data pipeline, the model,\n",
    "the loss function, and the gradient descent optimizer.\n",
    "While modern deep learning frameworks can automate nearly all of this work,\n",
    "implementing things from scratch is the only\n",
    "to make sure that you really know what you are doing.\n",
    "Moreover, when it comes time to customize models,\n",
    "defining our own layers, loss functions, etc.,\n",
    "understanding how things work under the hood will prove handy.\n",
    "In this section, we will rely only on `NDArray` and `GradientCollector`.\n",
    "Afterwards, we will introduce a more compact implementation,\n",
    "taking advantage of DJL's bells and whistles.\n",
    "To start off, we import the few required packages."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load ../utils/djl-imports\n",
    "%load ../utils/plot-utils"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Generating the Dataset\n",
    "\n",
    "To keep things simple, we will construct an artificial dataset\n",
    "according to a linear model with additive noise.\n",
    "Our task will be to recover this model's parameters\n",
    "using the finite set of examples contained in our dataset.\n",
    "We will keep the data low-dimensional so we can visualize it easily.\n",
    "In the following code snippet, we generated a dataset \n",
    "containing $1000$ examples, each consisting of $2$ features\n",
    "sampled from a standard normal distribution.\n",
    "Thus our synthetic dataset will be an object\n",
    "$\\mathbf{X}\\in \\mathbb{R}^{1000 \\times 2}$.\n",
    "\n",
    "The true parameters generating our data will be \n",
    "$\\mathbf{w} = [2, -3.4]^\\top$ and $b = 4.2$\n",
    "and our synthetic labels will be assigned according \n",
    "to the following linear model with noise term $\\epsilon$:\n",
    "\n",
    "$$\\mathbf{y}= \\mathbf{X} \\mathbf{w} + b + \\mathbf\\epsilon.$$\n",
    "\n",
    "You could think of $\\epsilon$ as capturing potential \n",
    "measurement errors on the features and labels.\n",
    "We will assume that the standard assumptions hold and thus\n",
    "that $\\epsilon$ obeys a normal distribution with mean of $0$.\n",
    "To make our problem easy, we will set its standard deviation to $0.01$.\n",
    "The following code generates our synthetic dataset:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "2"
    }
   },
   "outputs": [],
   "source": [
    "class DataPoints {\n",
    "    private NDArray X, y;\n",
    "    public DataPoints(NDArray X, NDArray y) {\n",
    "        this.X = X;\n",
    "        this.y = y;\n",
    "    }\n",
    "    \n",
    "    public NDArray getX() {\n",
    "        return X;\n",
    "    }\n",
    "    \n",
    "    public NDArray getY() {\n",
    "        return y;\n",
    "    }\n",
    "}\n",
    "\n",
    "// Generate y = X w + b + noise\n",
    "public DataPoints syntheticData(NDManager manager, NDArray w, float b, int numExamples) {\n",
    "    NDArray X = manager.randomNormal(new Shape(numExamples, w.size()));\n",
    "    NDArray y = X.matMul(w).add(b);\n",
    "    // Add noise\n",
    "    y = y.add(manager.randomNormal(0, 0.01f, y.getShape(), DataType.FLOAT32));\n",
    "    return new DataPoints(X, y);\n",
    "}\n",
    "\n",
    "NDManager manager = NDManager.newBaseManager();\n",
    "\n",
    "NDArray trueW = manager.create(new float[]{2, -3.4f});\n",
    "float trueB = 4.2f;\n",
    "\n",
    "DataPoints dp = syntheticData(manager, trueW, trueB, 1000);\n",
    "NDArray features = dp.getX();\n",
    "NDArray labels = dp.getY();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that each row in `features` consists of a 2-dimensional data point \n",
    "and that each row in `labels` consists of a 1-dimensional target value (a scalar)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "3"
    }
   },
   "outputs": [],
   "source": [
    "System.out.printf(\"features: [%f, %f]\\n\", features.get(0).getFloat(0), features.get(0).getFloat(1));\n",
    "System.out.println(\"label: \" + labels.getFloat(0));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By generating a scatter plot using the second feature `features[:, 1]` and `labels`, \n",
    "we can clearly observe the linear correlation between the two."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "18"
    }
   },
   "outputs": [],
   "source": [
    "float[] X = features.get(new NDIndex(\":, 1\")).toFloatArray();\n",
    "float[] y = labels.toFloatArray();\n",
    "\n",
    "Table data = Table.create(\"Data\")\n",
    "    .addColumns(\n",
    "        FloatColumn.create(\"X\", X),\n",
    "        FloatColumn.create(\"y\", y)\n",
    "    );\n",
    "\n",
    "ScatterPlot.create(\"Synthetic Data\", data, \"X\", \"y\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reading the Dataset\n",
    "\n",
    "Recall that training models consists of \n",
    "making multiple passes over the dataset, \n",
    "grabbing one minibatch of examples at a time,\n",
    "and using them to update our model. \n",
    "We can use `ArrayDataset` to randomly sample\n",
    "the data and access it in minibatches.\n",
    "\n",
    "In the following code, we instantiate an `ArrayDataset`.\n",
    "We then set parameters for `features`, `labels`, `batchSize`, \n",
    "and `sampling`. \n",
    "\n",
    "With `dataset.getData`, we can get minibatches of size `batchSize`,\n",
    "each consisting of its features and labels."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "5"
    }
   },
   "outputs": [],
   "source": [
    "import ai.djl.training.dataset.ArrayDataset;\n",
    "import ai.djl.training.dataset.Batch;\n",
    "\n",
    "int batchSize = 10;\n",
    "\n",
    "ArrayDataset dataset = new ArrayDataset.Builder()\n",
    "                          .setData(features) // Set the Features\n",
    "                          .optLabels(labels) // Set the Labels\n",
    "                          .setSampling(batchSize, false) // set the batch size and random sampling to false\n",
    "                          .build();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In general, note that we want to use reasonably sized minibatches\n",
    "to take advantage of the GPU hardware,\n",
    "which excels at parallelizing operations.\n",
    "Because each example can be fed through our models in parallel\n",
    "and the gradient of the loss function for each example can also be taken in parallel,\n",
    "GPUs allow us to process hundreds of examples in scarcely more time\n",
    "than it might take to process just a single example.\n",
    "\n",
    "To build some intuition, let us read and print\n",
    "the first small batch of data examples.\n",
    "The shape of the features in each minibatch tells us\n",
    "both the minibatch size and the number of input features.\n",
    "Likewise, our minibatch of labels will have a shape given by `batchSize`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "6"
    }
   },
   "outputs": [],
   "source": [
    "Batch batch = dataset.getData(manager).iterator().next();\n",
    "// Call head() to get the first NDArray\n",
    "NDArray X = batch.getData().head();\n",
    "NDArray y = batch.getLabels().head();\n",
    "System.out.println(X);\n",
    "System.out.println(y);\n",
    "// Don't forget to close the batch!\n",
    "batch.close();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As we run the iterator, we obtain distinct minibatches \n",
    "successively until all the data has been exhausted (try this).\n",
    "While the iterator implemented above is good for didactic purposes,\n",
    "it is inefficient in ways that might get us in trouble on real problems.\n",
    "For example, it requires that we load all data in memory\n",
    "and that we perform lots of random memory access.\n",
    "The built-in iterators implemented in DJL\n",
    "are considerably more efficient and they can deal\n",
    "both with data stored in file and data fed via a data stream.\n",
    "\n",
    "## Initializing Model Parameters\n",
    "\n",
    "Before we can begin optimizing our model's parameters by gradient descent,\n",
    "we need to have some parameters in the first place.\n",
    "In the following code, we initialize weights by sampling\n",
    "random numbers from a normal distribution with mean 0\n",
    "and a standard deviation of $0.01$, setting the bias $b$ to $0$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "7"
    }
   },
   "outputs": [],
   "source": [
    "NDArray w = manager.randomNormal(0, 0.01f, new Shape(2, 1), DataType.FLOAT32);\n",
    "NDArray b = manager.zeros(new Shape(1));\n",
    "NDList params = new NDList(w, b);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we have initialized our parameters,\n",
    "our next task is to update them until \n",
    "they fit our data sufficiently well.\n",
    "Each update requires taking the gradient\n",
    "(a multi-dimensional derivative)\n",
    "of our loss function with respect to the parameters.\n",
    "Given this gradient, we can update each parameter\n",
    "in the direction that reduces the loss.\n",
    "\n",
    "Since nobody wants to compute gradients explicitly\n",
    "(this is tedious and error prone),\n",
    "we use automatic differentiation to compute the gradient.\n",
    "See :numref:`sec_gradcollector` for more details.\n",
    "Recall from the autograd chapter\n",
    "that in order for `GradientCollector` to know\n",
    "that it should store a gradient for our parameters,\n",
    "we need to invoke the `attachGradient()` function,\n",
    "allocating memory to store the gradients that we plan to take."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Defining the Model\n",
    "\n",
    "Next, we must define our model,\n",
    "relating its inputs and parameters to its outputs.\n",
    "Recall that to calculate the output of the linear model,\n",
    "we simply take the matrix-vector dot product\n",
    "of the examples $\\mathbf{X}$ and the models weights $w$,\n",
    "and add the offset $b$ to each example.\n",
    "Note that below `X.dot(w)` is a vector and `b` is a scalar.\n",
    "Recall that when we add a vector and a scalar,\n",
    "the scalar is added to each component of the vector."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "9"
    }
   },
   "outputs": [],
   "source": [
    "// Saved in Training.java for later use\n",
    "public NDArray linreg(NDArray X, NDArray w, NDArray b) {\n",
    "    return X.dot(w).add(b);\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Defining the Loss Function\n",
    "\n",
    "Since updating our model requires taking \n",
    "the gradient of our loss function,\n",
    "we ought to define the loss function first.\n",
    "Here we will use the squared loss function\n",
    "as described in the previous section.\n",
    "In the implementation, we need to transform the true value `y` \n",
    "into the predicted value's shape `yHat`.\n",
    "The result returned by the following function\n",
    "will also be the same as the `yHat` shape."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "10"
    }
   },
   "outputs": [],
   "source": [
    "// Saved in Training.java for later use\n",
    "public NDArray squaredLoss(NDArray yHat, NDArray y) {\n",
    "    return (yHat.sub(y.reshape(yHat.getShape()))).mul \n",
    "        ((yHat.sub(y.reshape(yHat.getShape())))).div(2);\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Defining the Optimization Algorithm\n",
    "\n",
    "As we discussed in the previous section,\n",
    "linear regression has a closed-form solution.\n",
    "However, this is not a book about linear regression,\n",
    "it is a book about deep learning.\n",
    "Since none of the other models that this book introduces\n",
    "can be solved analytically, we will take this opportunity to introduce your first working example of stochastic gradient descent (SGD).\n",
    "\n",
    "\n",
    "At each step, using one batch randomly drawn from our dataset,\n",
    "we will estimate the gradient of the loss with respect to our parameters.\n",
    "Next, we will update our parameters (a small amount)\n",
    "in the direction that reduces the loss.\n",
    "Recall from :numref:`sec_gradcollector` that after we call `backward()`, \n",
    "each parameter (`param`) will have its gradient stored in `param.getGradient()`.\n",
    "The following code applies the SGD update,\n",
    "given a set of parameters, a learning rate, and a batch size.\n",
    "The size of the update step is determined by the learning rate `lr`.\n",
    "Because our loss is calculated as a sum over the batch of examples,\n",
    "we normalize our step size by the batch size (`batchSize`),\n",
    "so that the magnitude of a typical step size\n",
    "does not depend heavily on our choice of the batch size."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "11"
    }
   },
   "outputs": [],
   "source": [
    "// Saved in Training.java for later use\n",
    "public static void sgd(NDList params, float lr, int batchSize) {\n",
    "    for (int i = 0; i < params.size(); i++) {\n",
    "        NDArray param = params.get(i);\n",
    "        // Update param\n",
    "        // param = param - param.gradient * lr / batchSize\n",
    "        param.subi(param.getGradient().mul(lr).div(batchSize));\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training\n",
    "\n",
    "Now that we have all of the parts in place,\n",
    "we are ready to implement the main training loop.\n",
    "It is crucial that you understand this code\n",
    "because you will see nearly identical training loops\n",
    "over and over again throughout your career in deep learning.\n",
    "\n",
    "In each iteration, we will grab minibatches of training dataset,\n",
    "first passing them through our model to obtain a set of predictions.\n",
    "After calculating the loss, we call the `backward()` function\n",
    "to initiate the backwards pass through the network, \n",
    "storing the gradients with respect to each parameter in its corresponding `gradient` attribute. Technically since `NDArray` is an interface for each engine's implementation, there is no standard `gradient` attribute, but we can safely assume that we can access them however they are stored with `getGradient()`.\n",
    "Finally, we will call the optimization algorithm `sgd`\n",
    "to update the model parameters.\n",
    "Since we previously set the batch size `batchSize` to $10$,\n",
    "the loss shape `l` for each minibatch is ($10$, $1$).\n",
    "\n",
    "In summary, we will execute the following loop:\n",
    "\n",
    "* Initialize parameters $(\\mathbf{w}, b)$\n",
    "* Repeat until done\n",
    "    * Compute gradient $\\mathbf{g} \\leftarrow \\partial_{(\\mathbf{w},b)} \\frac{1}{\\mathcal{B}} \\sum_{i \\in \\mathcal{B}} l(\\mathbf{x}^i, y^i, \\mathbf{w}, b)$\n",
    "    * Update parameters $(\\mathbf{w}, b) \\leftarrow (\\mathbf{w}, b) - \\eta \\mathbf{g}$\n",
    "\n",
    "In the code below, `l` is a vector of the losses\n",
    "for each example in the minibatch.\n",
    "\n",
    "In each epoch (a pass through the data),\n",
    "we will iterate through the entire dataset\n",
    "(using the `dataset.getData()` function) once\n",
    "passing through every examples in the training dataset\n",
    "(assuming the number of examples is divisible by the batch size).\n",
    "The number of epochs `numEpochs` and the learning rate `lr` are both hyper-parameters, \n",
    "which we set here to $3$ and $0.03$, respectively. \n",
    "Unfortunately, setting hyper-parameters is tricky\n",
    "and requires some adjustment by trial and error.\n",
    "We elide these details for now but revise them\n",
    "later in\n",
    ":numref:`chap_optimization`.\n",
    "\n",
    "Note: We can replace `linreg` and `squaredLoss` with any net or loss function respectively\n",
    "and still keep the same training structure shown here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "12"
    }
   },
   "outputs": [],
   "source": [
    "float lr = 0.03f;  // Learning Rate\n",
    "int numEpochs = 3;  // Number of Iterations\n",
    "\n",
    "// Attach Gradients\n",
    "for (NDArray param : params) {\n",
    "    param.setRequiresGradient(true);\n",
    "}\n",
    "\n",
    "for (int epoch = 0; epoch < numEpochs; epoch++) {\n",
    "    // Assuming the number of examples can be divided by the batch size, all\n",
    "    // the examples in the training dataset are used once in one epoch\n",
    "    // iteration. The features and tags of minibatch examples are given by X\n",
    "    // and y respectively.\n",
    "    for (Batch batch : dataset.getData(manager)) {\n",
    "        NDArray X = batch.getData().head();\n",
    "        NDArray y = batch.getLabels().head();\n",
    "        \n",
    "        try (GradientCollector gc = Engine.getInstance().newGradientCollector()) {\n",
    "            // Clear the gradients from the previous batch\n",
    "            gc.zeroGradients();\n",
    "            // Minibatch loss in X and y\n",
    "            NDArray l = squaredLoss(linreg(X, params.get(0), params.get(1)), y);\n",
    "            gc.backward(l);  // Compute gradient on l with respect to w and b\n",
    "        }\n",
    "        sgd(params, lr, batchSize);  // Update parameters using their gradient\n",
    "        \n",
    "        batch.close();\n",
    "    }\n",
    "    NDArray trainL = squaredLoss(linreg(features, params.get(0), params.get(1)), labels);\n",
    "    System.out.printf(\"epoch %d, loss %f\\n\", epoch + 1, trainL.mean().getFloat());\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this case, because we synthesized the data ourselves,\n",
    "we know precisely what the true parameters are. \n",
    "Thus, we can evaluate our success in training \n",
    "by comparing the true parameters\n",
    "with those that we learned through our training loop. \n",
    "Indeed they turn out to be very close to each other."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "13"
    }
   },
   "outputs": [],
   "source": [
    "float[] w = trueW.sub(params.get(0).reshape(trueW.getShape())).toFloatArray();\n",
    "System.out.println(String.format(\"Error in estimating w: [%f, %f]\", w[0], w[1]));\n",
    "System.out.println(String.format(\"Error in estimating b: %f\", trueB - params.get(1).getFloat()));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that we should not take it for granted\n",
    "that we are able to recover the parameters accurately.\n",
    "This only happens for a special category problems:\n",
    "strongly convex optimization problems with \"enough\" data to ensure\n",
    "that the noisy samples allow us to recover the underlying dependency.\n",
    "In most cases this is *not* the case.\n",
    "In fact, the parameters of a deep network \n",
    "are rarely the same (or even close) between two different runs, \n",
    "unless all conditions are identical,\n",
    "including the order in which the data is traversed.\n",
    "However, in machine learning, we are typically less concerned\n",
    "with recovering true underlying parameters,\n",
    "and more concerned with parameters that lead to accurate prediction.\n",
    "Fortunately, even on difficult optimization problems,\n",
    "stochastic gradient descent can often find remarkably good solutions,\n",
    "owing partly to the fact that, for deep networks,\n",
    "there exist many configurations of the parameters \n",
    "that lead to accurate prediction.\n",
    "\n",
    "## Summary\n",
    "\n",
    "We saw how a deep network can be implemented\n",
    "and optimized from scratch, using just `NDArray` and `GradientCollector`,\n",
    "without any need for defining layers, fancy optimizers, etc.\n",
    "This only scratches the surface of what is possible.\n",
    "In the following sections, we will describe additional models\n",
    "based on the concepts that we have just introduced\n",
    "and learn how to implement them more concisely.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. What would happen if we were to initialize the weights $\\mathbf{w} = 0$. Would the algorithm still work?\n",
    "1. Assume that you are [Georg Simon Ohm](https://en.wikipedia.org/wiki/Georg_Ohm) trying to come up with a model between voltage and current. Can you use `GradientCollector` to learn the parameters of your model.\n",
    "1. Can you use [Planck's Law](https://en.wikipedia.org/wiki/Planck%27s_law) to determine the temperature of an object using spectral energy density?\n",
    "1. What are the problems you might encounter if you wanted to extend `GradientCollector` to second derivatives? How would you fix them?\n",
    "1.  Why is the `reshape()` function needed in the `squaredLoss()` function?\n",
    "1. Experiment using different learning rates to find out how fast the loss function value drops.\n",
    "1. If the number of examples cannot be divided by the batch size, what happens to the `dataset.getData()` function's behavior?\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "14.0.2+12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
